
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：服务费(手续费)                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-01-29 17:12:18                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： ServiceChargeService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using AutoMapper;
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using BestTrader.Cms.Models;
using BestTrader.Cms.RmmfSoftServices;
using BestTrader.Cms.RmmfSoftServices.Models;
using BestTrader.Cms.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BestTrader.Cms.Services
{
    public class ServiceChargeService: IServiceChargeService
    {
        private readonly IServiceChargeRepository _repository;
        private readonly IManagerRepository _managerRepository;
        private readonly ISysItemsDetailService _itemsService;
        private readonly RmmfSoftCashService _rmmfService;
        private readonly IMapper _mapper;

        public ServiceChargeService(IServiceChargeRepository repository, IManagerRepository managerRepository, ISysItemsDetailService itemsService, RmmfSoftCashService rmmfService, IMapper mapper)
        {
            _repository = repository;
            _managerRepository = managerRepository;
            _itemsService = itemsService;
            _rmmfService = rmmfService;
            _mapper = mapper;
        }

        public BaseResult AddOrModify(ServiceChargeAddOrModifyModel item, string UserId)
        {
            var result = new BaseResult();
            ServiceCharge entity;
            var userId = UserId.ToInt32() ?? 0;
            var now = DateTime.Now;
            if (item.Id == 0)
            {
                ////TODO ADD
                //entity = _mapper.Map<ServiceCharge>(item);
                //entity.AddManagerId = userId;
                //entity.IsDefault = false;
                //entity.IsDelete = false;
                //entity.AddTime = now;
                //if (_repository.Insert(entity) > 0)
                //{
                //    result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                //    result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                //}
                //else
                //{
                //    result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                //    result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                //}
            }
            else
            {
                //TODO Modify
                entity = _repository.Get(item.Id);
                if (entity != null)
                {
                    //_mapper.Map(item, entity);
                    entity.ProjectPrice = item.ProjectPrice;
                    entity.ProjectTime = now;
                    entity.ModifyManagerId = userId;
                    entity.ModifyTime = now;
                    if (_repository.Update(entity) > 0)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else
                {
                    result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                    result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                }
            }
            return result;
        }

        private List<FeeRulesByAccountNameOutput> GetRmmfFeeRules(string userName)
        {
            var result = _rmmfService.GetFeeRulesByAccountName(userName);
            return result;
        }

        private bool CreateOrUpdateRmmfFeeRule(FeeRulesByAccountNameOutput item, string userName, string fpExchangeCode, decimal fPFeeRate) {
            int fpDefinitionID = item.Fee_DefinationID;
            int fPFeeType = item.Fee_Type;
            //decimal fPFeeRate = 125;// item.Fee_Rate;
            string fpCurrencyCode = item.Fee_CurrencyCode;
            //string fpExchangeCode = sysItems.GetItems("ExchangeCode").FirstOrDefault(p => p.ItemCode == "BO").ItemData;
            //string fpExchangeCode = "CBT";
            string fpProductCode = item.PF_Code;
            int fpProduct_Kind = item.Kind;
            var res = _rmmfService.InsertFeeRule(fpDefinitionID, fPFeeType, fPFeeRate, fpCurrencyCode, userName, fpExchangeCode, fpProductCode, fpProduct_Kind);

            return res > 0;
        }

        /// <summary>
        ///  删除风软接口
        /// </summary>
        /// <param name="fpDefinitionID"></param>
        /// <param name="fpProduct_Kind"></param>
        /// <param name="userName"></param>
        /// <param name="fpExchangeCode"></param>
        /// <param name="fpProductCode"></param>
        /// <returns></returns>
        private bool DeleteRmmfFeeRule(int fpDefinitionID, int fpProduct_Kind, string userName,string fpExchangeCode,string fpProductCode)
        {
            var res = _rmmfService.DeleteFeeRuleByAccount(fpDefinitionID, fpProduct_Kind, userName, fpExchangeCode,fpProductCode);
            return res > 0;
        }

        /// <summary>
        /// 批量处理直客的手续费
        /// </summary>
        /// <param name="model"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public BaseResult BatchAddOrModify(List<UserTradeModel> model, String UserId) {
            var result = new BaseResult();
            ServiceCharge entity;
            var userId = UserId.ToInt32() ?? 0;
            var now = DateTime.Now;

            // 获取所有的机构码
            var exchangeCodes = _itemsService.GetItems("ExchangeCode");
            // 批处理某一个用户的数据，获取第一条就OK
            var firstModel = model.FirstOrDefault();
            var feeRules = new List<FeeRulesByAccountNameOutput>();
            var firstName = "";
            if (firstModel != null)
            {
                if (firstModel.ProjectManagerId.HasValue)
                {
                    var currentManager = _managerRepository.Get(firstModel.ProjectManagerId.Value);
                    feeRules = GetRmmfFeeRules(currentManager.UserName);
                    firstName = currentManager.UserName;
                }
                else
                {
                    // 默认规则不同步风软件
                }
            }

            foreach (var item in model)
            {
                if (!firstName.IsNullOrWhiteSpace())
                {
                    var exchangeCode = exchangeCodes.FirstOrDefault(p => p.ItemCode == item.ProjectCode);
                    if (exchangeCode==null) {
                        continue;
                    }
                    var feeRule = feeRules.FirstOrDefault(p => p.PF_Code == exchangeCode.ItemCode);
                    if (exchangeCode != null && feeRule != null)
                    {
                        // 计算总手续费
                        if (item.AgentTrade.HasValue || item.SalesTrade.HasValue)
                        {
                            var feeRate = (item.AgentTrade ?? 0) + (item.SalesTrade ?? 0);
                            // 不同于风软的规则
                            if (feeRule.Fee_Rate != feeRate)
                            {
                                // 删除风软自定义规则
                                var delFlag = DeleteRmmfFeeRule(feeRule.Fee_DefinationID, feeRule.Kind, firstName, exchangeCode.ItemData,feeRule.PF_Code);
                                // 添加新的规则
                                var flag = CreateOrUpdateRmmfFeeRule(feeRule, firstName, exchangeCode.ItemData, feeRate);
                                if (flag)
                                {
                                    // 重新生成成功
                                }
                            }
                        }
                        else
                        {
                            //// 删除风软自定义规则
                            //var delFlag = DeleteRmmfFeeRule(feeRule.Fee_DefinationID, feeRule.Kind, firstName);
                            //if (delFlag)
                            //{
                            //    // 重新生成成功
                            //}
                        }
                    }
                }

                #region 保存用户多条返佣记录，获取新的一条记录 2019-03-27
                // 判断直客的数据是否有变化，当返佣和成本没有变化时，不更新数据
                var isExist = _repository.Get($"select top 1 * from ServiceCharge where IsDefault = 0 and ProjectManagerId={item.ProjectManagerId} and ProjectCode='{item.ProjectCode}' and AgentTrade={item.AgentTrade} and SalesTrade={item.SalesTrade} ");
                if (isExist == null)
                {
                    entity = _mapper.Map<ServiceCharge>(item);
                    entity.ProjectTime = now;
                    entity.AddManagerId = userId;
                    entity.IsDefault = false;
                    entity.IsDelete = false;
                    entity.AddTime = now;
                    if (_repository.Insert(entity) > 0)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }
                else {

                    isExist.AddTime = now;
                    isExist.ModifyTime = now;
                    isExist.ModifyManagerId = UserId.ToInt32();
                    if (_repository.Update(isExist) > 0)
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                    }
                    else
                    {
                        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                    }
                }

                //if (item.Id == 0)
                //{
                //    entity = _mapper.Map<ServiceCharge>(item);
                //    entity.ProjectTime = now;
                //    entity.AddManagerId = userId;
                //    entity.IsDefault = false;
                //    entity.IsDelete = false;
                //    entity.AddTime = now;
                //    if (_repository.Insert(entity) > 0)
                //    {
                //        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                //        result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                //    }
                //    else
                //    {
                //        result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                //        result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                //    }
                //}
                //else
                //{
                //    entity = _repository.Get(item.Id);
                //    if (entity != null)
                //    {
                //        entity.AgentTrade = item.AgentTrade;
                //        entity.SalesTrade = item.SalesTrade;
                //        entity.ProjectPrice = item.ProjectPrice;
                //        entity.ProjectTime = now;
                //        entity.ModifyManagerId = userId;
                //        entity.ModifyTime = now;
                //        if (_repository.Update(entity) > 0)
                //        {
                //            result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                //            result.ResultMsg = ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                //        }
                //        else
                //        {
                //            result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                //            result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
                //        }
                //    }
                //    else
                //    {
                //        result.ResultCode = ResultCodeAddMsgKeys.CommonFailNoDataCode;
                //        result.ResultMsg = ResultCodeAddMsgKeys.CommonFailNoDataMsg;
                //    }
                //} 

                #endregion
            }
            
            return result;
        }

        public TableDataModel LoadData(ServiceChargeRequestModel model, string userId, string roleId)
        {
            string conditions = "where IsDelete=0 and IsDefault =1 ";// 未删除的所有默认记录
            string Key = "";
            if (!model.Key.IsNullOrWhiteSpace())
            {
                conditions += $"and (ProjectName like @Key or ProjectCode like @Key )";
                Key = model.Key.ToSqlLikeParam();
            }
            var list = _repository.GetListPaged(model.Page, model.Limit, conditions, "Id desc",new { Key=Key}).ToList();
            var viewList = new List<ServiceChargeListModel>();
            list.ForEach(x => {
                var item = _mapper.Map<ServiceChargeListModel>(x);
                if (x.ProjectManagerId.HasValue)
                    item.ProjectManagerName = _managerRepository.GetUserNameAndRealNameById(x.ProjectManagerId.Value);
                viewList.Add(item);
            });
            return new TableDataModel
            {
                count = _repository.RecordCount(conditions, new { Key = Key }),
                data = viewList,
            };
        }

        public List<ItemsDetailModel> GetDefaultTradeCommissionItems()
        {
            var result = new List<ItemsDetailModel>();

            string conditions = "WHERE IsDelete=0 ";//未删除的
            var data = _repository.GetList(conditions);
            if (data.Any())
            {
                foreach (var item in data)
                {
                    result.Add(new ItemsDetailModel
                    {
                        ItemCode = item.ProjectPrice.ToString(),
                        ItemName = item.ProjectName,
                        ItemData = item.ProjectCode
                    });
                }
            }
            return result;
        }

        public List<ServiceChargeListModel> LoadServiceCharges(bool isDefault = false)
        {
            string conditions = "WHERE IsDelete=0 ";//未删除的
            if (isDefault)
            {
                conditions += "AND IsDefault=1 ";
            }
            var data = _repository.GetList(conditions);
            return _mapper.Map<List<ServiceChargeListModel>>(data);
        }

        public List<ServiceChargeListModel> GetServiceChargesById(int managerId) {
            string conditions = $"WHERE IsDelete=0 and ProjectManagerId = {managerId} order by AddTime ";//未删除的
            var data = _repository.GetList(conditions);
            return _mapper.Map<List<ServiceChargeListModel>>(data);
        }

        public List<ServiceChargeListModel> GetHistoryByManagerId(ServiceChargeHistoryQueryModel item) {
            string conditions = $"WHERE IsDelete=0 and ProjectManagerId = {item.ManagerId} and ProjectCode = '{item.ProjectCode}' order by AddTime desc ";//未删除的
            var data = _repository.GetList(conditions);
            return _mapper.Map<List<ServiceChargeListModel>>(data);
        }

    }
}